package logic

import (
	"context"
	"encoding/json"
	cache2 "furni-manage/cache"
	"furni-manage/model/mysql"
	"time"

	"furni-manage/goods/goods"
	"furni-manage/goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *goods.GoodsListRequest) (*goods.GoodsListResponse, error) {
	// todo: add your logic here and delete this line

	var data []*goods.GoodList

	/*
		SELECT
		  goods.`name` AS goods_name,
		  goods.id AS goods_id,
		  goods.price,
		  goods.num,
		  goods.image,
		  classes.`name` AS classes_name,
		  goods.created_at
		FROM
		  goods
		  LEFT JOIN classes ON classes.id = goods.class_id
	*/
	cache, _ := cache2.Rdb.Get(l.ctx, "list").Result()
	if cache == "" {
		data = mysql.GoodsList(mysql.DB, data)
		jsonData, _ := json.Marshal(data)
		cache2.Rdb.Set(l.ctx, cache, jsonData, time.Minute*10)
	} else {
		json.Unmarshal([]byte(cache), &data)
	}

	return &goods.GoodsListResponse{
		List: data,
	}, nil
}
